package com.wyp168.juc;

import java.util.Objects;

/**
 * @ClassName ThreadLocalDemo001
 * @Description TODO
 * @Author wyp168
 * @Date 2022/7/8 16:09
 */
public class ThreadLocalDemo001 implements Runnable{
    public ThreadLocal<String> threadLocal = new ThreadLocal<>();
    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new ThreadLocalDemo001(), "AA");
        Thread threadB = new Thread(new ThreadLocalDemo001(), "BB");

        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();

        System.out.println("All of Task have finished...");
    }

    public void print(String str) {
        //调用threadLocal对象的get()方法，获取本地变量副本
        while(!Objects.isNull(threadLocal.get())) {
            System.out.println(str + " : " + threadLocal.get());
            threadLocal.remove();
        }
    }


    @Override
    public void run() {
        threadLocal.set(Thread.currentThread().getName() + "---Value01");
        threadLocal.set(Thread.currentThread().getName() + "---Value02");
        print(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getName() + "   remove value of threadLocal");
    }
}
